const Groups = require('./Groups')
const userHelp=require('../users/userHelp')
const msgHelp=require('../msgs/msgHelp')
const UnReadMsgHelp=require('../unread/UnReadMsgHelp')
const Msgs=require('../msgs/Msgs')



//获取某个用户的群列表
exports.getGroupList=async (uid) => {

    let list=await Groups.find().sort('gid')
    let lists_ =list.filter((item,index)=>{
        let userlist=JSON.parse(item.userlist)
        let flag=false
        userlist.map((obj,index)=>{
            if(obj.uid==uid-0){
                flag=true
            }
        })
        return flag
    })
    return lists_
}



exports.getGroupNum=async () => {

    let num=await Groups.find().count()

    return num
}



//群是否存在，用户是否在群里面
exports.isGroupExist=async (gid,uid) => {
    let data=await Groups.findOne({gid:gid-0})

    if(data){
        let in_group=false
        let uids=await  getGroupUserIds(gid-0)
        
        for(let item of uids){
            if(item==uid){
                in_group=true
                break
            }
        }
        if(in_group){
          return {
              is_exist:true,
              in_group:true
          }
        }else{
            return {
                is_exist:true,
                in_group:false
            }
        }
    }
    return {
        is_exist:false,
    }
}



//获取群消息
exports.getGroupInfo=async (gid) => {

    let data=await Groups.findOne({gid:gid})

    return data
}


exports.getGroupInfoByGname=async (gname) => {

    let reg=new RegExp(gname, "g");

    let data=await Groups.find({
        gname:{
            $regex:reg
        }
    })

    return data
}


//获取群用户
exports.getGroupUserList=async (gid) => {

    let data=await Groups.findOne({gid:gid})
    let userlist=JSON.parse(data.userlist)

    return userlist
}



//获取群用户id
const getGroupUserIds=async (gid)=>{
    let data=await Groups.findOne({gid:gid})
    
    let userlist=JSON.parse(data.userlist) 

    let user_ids=[]

    for(let user of userlist){
        user_ids.push(user.uid)
    }

    return user_ids
}
exports.getGroupUserIds=getGroupUserIds




//判断用户是否在群里面
const isUserInGroup=async (gid,uid)=>{
    let userids=getGroupUserIds(gid)
    for(let item of userids){
        if(uid==item){
            return true
        }
    }
    return false
}
exports.isUserInGroup=isUserInGroup






//修改群名称
exports.changeGroupName=async (gid,gname) => {
    let oriData=await Groups.findOne({gid:gid})
    oriData=Object.assign(oriData,{gname:gname})
    let data=await Groups.update({gid:gid},oriData)

    return data
}



//退出群聊
exports.exitGroup=async (gid,myuid) => {
    let data=await Groups.findOne({gid:gid-0})
    let userlist=JSON.parse(data.userlist)


    let index=-1
    for(let i=0; i<userlist.length; i++){
        if(userlist[i].uid==myuid-0){
            index=i
            break;
        }
    }
    if(index>-1){
        userlist.splice(index,1)
    }

    let new_group_info=Object.assign(data,{userlist:JSON.stringify(userlist)})
    await Groups.update({gid:gid},new_group_info)
    return ''
}




//华人街,创建群,并将群主写入用户列表
exports.hrjCreateGroup=async (owner_uid,gname) => {

    let time=new Date().getTime()
    let owner_info=await userHelp.getUserInfo(owner_uid)

    let userlist=[owner_info]

    let obj={
        gid:time,
        owner_uid:owner_uid,
        gname:gname,
        userlist:JSON.stringify(userlist)
    }

    let group=new Groups(obj)
    await group.save()
    return obj
}



//华人街,添加群用户
exports.hrjAddGroupUser=async (gid,add_uids)=>{
    let data=await Groups.findOne({gid:gid-0})
    let userlist=JSON.parse(data.userlist)
    let add_userlist=[]
    let add_uids_arr=add_uids.split(',')

    let group_user_num=add_uids_arr.length+userlist.length

    if(group_user_num>200){

        return {
            code:-1,
            msg:'添加失败，群成员不能超过200人'
        }
    }


    for(let uid of add_uids_arr){

        let userinfo=await userHelp.getUserInfo(uid-0)

        if(userinfo.code==1){   //聊天服务器中不存在该用户

        }
        else{
            userlist.push(userinfo)
            add_userlist.push(userinfo)
        }
    }

    let new_group_info=Object.assign(data,{userlist:JSON.stringify(userlist)})
    await Groups.update({gid:gid-0},new_group_info)
    return {
        code:1,
        msg:'添加成功',
        userlist,
    }
}



//华人街,删除群
exports.hrjDeleteGroup=async (gid,owner_uid) => {

    let groupInfo=await Groups.findOne({gid:gid})
    if(owner_uid!=groupInfo.owner_uid){
        return {
            code:11,
            msg:`只有群主才能解散群组`
        }
    }


    //还要删群聊天室相应的消息
    await Msgs.remove({gid:gid})
    await UnReadMsgHelp.removeMsgByGid(gid)

    await Groups.remove({gid:gid})
    return ''

}




//华人街,删除群用户
exports.hrjRemoveGroupUser=async (gid,add_uids,myuid) => {
    console.log(gid,add_uids,myuid)
    let groupInfo=await Groups.findOne({gid:gid})

    if(myuid!=groupInfo.owner_uid){
        return {
            code:-1,
            msg:`只有群主才能删除用户`
        }
    }

    let userlist=JSON.parse(groupInfo.userlist)

    let add_uids_arr=add_uids.split(',')

    let userlist_copy=JSON.parse(JSON.stringify(userlist))
    for(let uid of add_uids_arr){
        let userlist_=JSON.parse(JSON.stringify(userlist))
        let index=getUserIndex(uid,userlist_)
        userlist_copy.splice(index,1)
    }

    let new_group_info=Object.assign(groupInfo,{userlist:JSON.stringify(userlist_copy)})
    await Groups.update({gid:gid},new_group_info)

    return ''
}


const getUserIndex=function (uid,userlist) {

    for(let i=0; i<userlist.length; i++){
        if(userlist[i].uid==uid){
            return i
        }
    }
    return -1
}










